<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input
        v-model="listQuery.title"
        placeholder="Title"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.importance"
        placeholder="Imp"
        clearable
        style="width: 90px"
        class="filter-item"
      >
        <el-option
          v-for="item in importanceOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <el-select
        v-model="listQuery.type"
        placeholder="Type"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in calendarTypeOptions"
          :key="item.key"
          :label="item.display_name + '(' + item.key + ')'"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-model="listQuery.sort"
        style="width: 140px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in sortOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        Search
      </el-button> -->
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        Add
      </el-button>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        Export
      </el-button>
      <el-checkbox
        v-model="showReviewer"
        class="filter-item"
        style="margin-left: 15px"
        @change="tableKey = tableKey + 1"
      >
        reviewer
      </el-checkbox>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      stripe
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column align="center" type="index" label="序号" fixed="left">
        <!-- <template slot-scope="scope">
          {{ scope.index }}
        </template> -->
      </el-table-column>
      <el-table-column
        label="ID"
        prop="id"
        fixed="left"
        sortable="custom"
        align="center"
        min-width="50px"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="登录名"
        fixed="left"
        align="center"
        min-width="150px"
      >
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">{{
            row.name
          }}</span>
          <!-- <el-tag>{{ row.type | typeFilter }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center" min-width="150px">
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">{{
            row.nickName
          }}</span>
          <!-- <el-tag>{{ row.type | typeFilter }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" min-width="50px">
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">{{
            row.sex
          }}</span>
          <!-- <el-tag>{{ row.type | typeFilter }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="角色类别" align="center" min-width="80px">
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">{{
            row.roleName
          }}</span>
          <!-- <el-tag>{{ row.type | typeFilter }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" min-width="150px">
        <template slot-scope="{ row }">
          <!-- <span class="link-type" @click="handleUpdate(row)"></span> -->
          <el-image
            style="width: 100px; height: 100px"
            :src="getImgURL(row.titlePic)"
            :preview-src-list="new Array(getImgURL(row.titlePic))"
          />

          <!-- <el-tag>{{ row.type | typeFilter }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" min-width="150px">
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">{{
            row.address
          }}</span>
          <!-- <el-tag>{{ row.type | typeFilter }}</el-tag> -->
        </template>
      </el-table-column>
      <!-- <el-table-column label="Date" width="150px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.timestamp | parseTime("{y}-{m}-{d} {h}:{i}") }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="Title" min-width="150px">
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">{{
            row.title
          }}</span>
          <el-tag>{{ row.type | typeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Author" width="110px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="showReviewer"
        label="Reviewer"
        width="110px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span style="color: red">{{ row.reviewer }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Imp" width="80px">
        <template slot-scope="{ row }">
          <svg-icon
            v-for="n in +row.importance"
            :key="n"
            icon-class="star"
            class="meta-item__icon"
          />
        </template>
      </el-table-column>
      <el-table-column label="Readings" align="center" width="95">
        <template slot-scope="{ row }">
          <span
            v-if="row.pageviews"
            class="link-type"
            @click="handleFetchPv(row.pageviews)"
            >{{ row.pageviews }}</span
          >
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="Status" class-name="status-col" width="100">
        <template slot-scope="{ row }">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column
        label="用户操作"
        align="center"
        max-width="80px"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="{ row, $index }">
          <el-button
            style="margin-bottom: 5px; margin-left: 10px; float: left"
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
          >
            修改信息
          </el-button>
          <!-- 只有Admin能操作降低或升高用户权限 -->
          <el-button
            v-if="row.roleName != 'Admin'&&currentRoles.indexOf('Admin')>-1"
            size="mini"
            type="success"
            style="margin-bottom: 5px; float: left"
            @click="handleAscensionAppUser(row)"
          >
            升级权限
          </el-button>
          <el-button
            v-if="row.roleName != 'User'&&currentRoles.indexOf('Admin')>-1"
            size="mini"
            type="warning"
            style="margin-bottom: 5px; float: left"
            @click="handleReduceAppUser(row)"
          >
            降低权限
          </el-button>
          <!-- <el-button
            v-if="row.status != 'draft'"
            size="mini"
            style="margin-bottom:5px;float:left;"
            @click="handleModifyStatus(row, 'draft')"
          >
            Draft
          </el-button> -->
          <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="info"
            style="margin-bottom: 5px; float: left"
            @click="handleChangePassword(row)"
          >
            修改密码
          </el-button>
          <!-- 只有Admin能删除用户 -->
          <el-button
            v-if="row.roleName != 'Admin'&&currentRoles.indexOf('Admin')>-1"
            size="mini"
            type="danger"
            style="margin-bottom: 5px; float: left"
            @click="handleDelete(row, $index)"
          >
            删&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getUserListPaged"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="登录名" prop="name">
          <el-input
            v-model="temp.name"
            class="filter-item"
            placeholder="请输入登录名"
            :disabled="dialogStatus !== 'create'"
            @input="checkUserName"
          />
        </el-form-item>
        <el-form-item
          v-show="dialogStatus === 'create'"
          label="密码"
          prop="password"
        >
          <el-input
            v-model="temp.password"
            class="filter-item"
            placeholder="请输入密码"
            type="password"
          />
        </el-form-item>
        <el-form-item
          v-show="dialogStatus === 'update'"
          label="昵称"
          prop="nickName"
        >
          <el-input
            v-model="temp.nickName"
            class="filter-item"
            placeholder="请输入昵称"
          />
        </el-form-item>
        <el-form-item
          v-show="dialogStatus === 'update'"
          label="地址"
          prop="address"
        >
          <el-input
            v-model="temp.address"
            class="filter-item"
            placeholder="请输入地址"
          />
        </el-form-item>
        <el-form-item
          v-show="dialogStatus === 'update'"
          label="角色类型"
          prop="roleId"
        >
          <el-select
            v-model="temp.roleId"
            class="filter-item"
            placeholder="请选择角色类型"
            :disabled="dialogStatus !== 'create'"
          >
            <el-option
              v-for="(item, index) in roles"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-show="dialogStatus === 'update'"
          label="性别"
          prop="sex"
        >
          <el-select
            v-model="temp.sex"
            class="filter-item"
            placeholder="请选择性别"
          >
            <!-- <el-option v-for="(item,index) in roles" :key="index" :label="item.name" :value="item.id" />
             -->
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-show="dialogStatus === 'update'"
          label="头像"
          prop="titlePic"
        >
        <!-- 添加一个引用，方便在上传图片成功后将其变为不可见 -->
          <el-image
            v-show="temp.titlePic"
            style="width: 100px; height: 100px"
            :src="getImgURL(temp.titlePic)"
            :preview-src-list="new Array(getImgURL(temp.titlePic))"
            ref="userImg"
          />
          <Upload
            v-show="temp.titlePic"
            action-u-r-l="UserPic"
            @returnUrl="handleUploadSuccess"
          />
        </el-form-item>

        <!-- <el-form-item label="Date" prop="timestamp">
          <el-date-picker
            v-model="temp.timestamp"
            type="datetime"
            placeholder="Please pick a date"
          />
        </el-form-item>
        <el-form-item label="Title" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>

        <el-form-item label="Title" prop="title">
          <Upload actionURL="UserPic" @returnUrl="handleUploadSuccess"></Upload>
        </el-form-item>

        <el-form-item label="Status">
          <el-select
            v-model="temp.status"
            class="filter-item"
            placeholder="Please select"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Imp">
          <el-rate
            v-model="temp.importance"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            :max="3"
            style="margin-top: 8px"
          />
        </el-form-item>
        <el-form-item label="Remark">
          <el-input
            v-model="temp.remark"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="Please input"
          />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 修改密码Dialog -->
    <el-dialog title="修改密码" :visible.sync="changePassworddialogFormVisible">
      <el-form
        ref="changePasswordDataForm"
        :rules="changePasswordDataFormRules"
        :model="changePasswordTemp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="ID" prop="id">
          <el-input
            v-model="changePasswordTemp.id"
            class="filter-item"
            placeholder="请输入ID"
            :disabled="dialogStatus === 'changePassword'"
          />
        </el-form-item>
        <el-form-item label="登录名" prop="name">
          <el-input
            v-model="changePasswordTemp.name"
            class="filter-item"
            placeholder="请输入登录名"
            :disabled="dialogStatus === 'changePassword'"
          />
        </el-form-item>
        <el-form-item
          v-show="dialogStatus === 'changePassword'"
          label="原密码"
          prop="password"
        >
          <el-input
            v-model="changePasswordTemp.password"
            class="filter-item"
            placeholder="请输入原密码"
            type="password"
          />
        </el-form-item>
        <el-form-item
          v-show="dialogStatus === 'changePassword'"
          label="新密码"
          prop="password"
        >
          <el-input
            v-model="changePasswordTemp.newPassword"
            class="filter-item"
            placeholder="请输入新密码"
            type="password"
          />
        </el-form-item>
        <el-form-item
          v-show="dialogStatus === 'changePassword'"
          label="确认新密码"
          prop="confirmNewPassword"
        >
          <el-input
            v-model="changePasswordTemp.confirmNewPassword"
            class="filter-item"
            placeholder="请确认新密码"
            type="password"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changePassworddialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="changePassword"> 确认 </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table
        :data="pvData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="dialogPvVisible = false"
        >Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
import {
  fetchUserListByRoleId,
  fetchUserList,
  fetchUserListPaged,
  createUser,
  getInfo,
  createPm,
  UpdateInfo,
  AscensionAppUser,
  ReduceAppUser,
  ChangePassword,
  DeleteAppUserInfo
} from '@/api/user'
import { getRoles } from '@/api/role'

import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

import Upload from '@/components/Upload/Upload.vue'

import {baseImgURL} from '@/utils/constTool.js'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination, Upload },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    // 自定义验证确认密码规则
    var validatePass = (rule, value, callback) => {
      if (value !== this.changePasswordTemp.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    return {
      // 封装roles对象
      roles: [],

      // 于模板基础之上自定义data
      baseImgURL: baseImgURL,
      srcList: [],

      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 3,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id',
        roleId: undefined
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,

      // 用于暂时存放add、Update方法的model对象
      temp: {
        id: undefined, // 编号
        name: '', // 登录名
        nickName: '', // 昵称
        address: '', // 地址
        roleId: '', // 角色id
        roleName: '', // 角色名称
        sex: '', // 性别
        titlePic: '', // 头像
        password: '' // 密码
      },

      // 用于暂时存放 修改密码 方法的model对象
      changePasswordTemp: {
        id: undefined, // 编号
        name: '',
        password: '', // 密码
        newPassword: '',
        confirmNewPassword: ''
      },
      changePassworddialogFormVisible: false,
      changePasswordDataFormRules: {
        id: [
          {
            required: true,
            message: 'id不能为空',
            trigger: 'blur'
          }
        ],
        name: [
          { required: true, message: '登录名不能为空', trigger: 'change' },
          { min: 4, max: 8, message: '长度在 4 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'change' },
          { min: 4, max: 8, message: '长度在 4 到 8 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '密码不能为空', trigger: 'change' },
          { min: 4, max: 8, message: '长度在 4 到 8 个字符', trigger: 'blur' }
        ],
        confirmNewPassword: [
          { required: true, message: '密码不能为空', trigger: 'change' },
          { min: 4, max: 8, message: '长度在 4 到 8 个字符', trigger: 'blur' },
          {
            validator: validatePass,
            trigger: 'blur'
          }
        ]
      },

      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑用户信息',
        create: '新增用户'
      },

      dialogPvVisible: false,
      pvData: [],
      rules: {
        // id:[{
        //   required:true,message:"id不能为空",trigger:"blur"
        // }],
        name: [
          { required: true, message: '登录名不能为空', trigger: 'change' },
          { min: 4, max: 8, message: '长度在 4 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'change' },
          { min: 4, max: 8, message: '长度在 4 到 8 个字符', trigger: 'blur' }
        ],
        nickName: [
          { max: 35, message: '长度不能超过35个字符', trigger: 'blur' }
        ],
        address: [
          { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
        ],
        id: [
          {
            required: true,
            message: '角色不能为空',
            trigger: 'blur'
          }
        ],
        sex: [
          {
            required: true,
            message: '角色不能为空',
            trigger: 'blur'
          }
        ]
      },
      downloadLoading: false
    }
  },
  computed: {
    // 在计算属性中拿到当前登录用户role令牌
    currentRoles() {
      return this.$store.state.user.roles
    }
  },
  created() {
    // // 更新roleId
    // this.listQuery.roleId = this.$route.query.roleId;
    // // console.log(this.listQuery.roleId);
    // if (this.listQuery.roleId) {
    //   this.getUserListByRoleId(this.listQuery.roleId);
    // } else {
    //   this.getUserList();
    // }
    this.loadData()

    // console.log(this.currentRoles.indexOf('Admin')>-1);
    // console.log(this.list);
  },
  methods: {
    // 加载数据列表开始
    loadData() {
      // 更新roleId
      this.listQuery.roleId = this.$route.query.roleId
      // console.log(this.listQuery.roleId);
      if (this.listQuery.roleId) {
        this.getUserListByRoleId(this.listQuery.roleId)
      } else {
        this.getUserList()
      }
    },
    // 加载数据列表结束

    // 加载数据列表开始
    loadDataPaged(data) {
      // console.log('loadDataPaged');
      // console.log(data);
      const that = this.list
      this.list = that.slice((data.page - 1) * data.limit, limit)

      // 更新roleId
      // this.listQuery.roleId = this.$route.query.roleId;
      // // console.log(this.listQuery.roleId);
      // if (this.listQuery.roleId) {
      //   this.getUserListByRoleId(this.listQuery.roleId);
      // } else {
      //   this.getUserList();
      // }
    },
    // 加载数据列表结束

    // 检查用户名是否已经存在开始
    checkUserName() {
      console.log('检查用户名')
    },
    // 检查用户名是否已经存在结束

    // 获取role开始
    getRoles() {
      // console.log("getRoles");
      getRoles().then((response) => {
        // 此处默认指定不可以自行添加Admin，故从数组中删除Admin
        // this.roles=response.data.pop();
        this.roles = response.data
        // console.log(this.roles);
        // return data;
        // data=response.data;
        // console.log(data);
        // console.log(this.roles);
      })
    },
    // 获取role结束

    // getRolesExceptAdmin开始
    getRolesExceptAdmin() {
      // console.log("getRoles");
      getRoles().then((response) => {
        // 此处默认指定不可以自行添加Admin，故从数组中删除Admin
        // this.roles=response.data.pop();
        // const data = response.data;
        // data.pop();

        const data = response.data
        data.pop()
        this.roles = data
      })
    },
    // getRolesExceptAdmin结束

    // 上传图片成功后，更新信息
    handleUploadSuccess(imageName) {
      this.temp.titlePic = imageName
      // console.log(imageName);
      var el= this.$refs['userImg'].$el;
      // console.log(el);
      el.style.display='none'
    },

    //  返回生成好的imgURL,如果参数为空,则自动补成默认
    getImgURL(imgName) {
      if (imgName === '' || imgName === null) {
        // this.srcList=[];
        // this.srcList.push(this.baseImgURL + "Default.jpg");
        return this.baseImgURL + 'Default.jpg'
      }
      // this.srcList=[];
      // this.srcList.push(this.baseImgURL + imgName);

      return this.baseImgURL + imgName
    },

    // 根据roleid拿到所有的User，如果roleid为空，则默认拿到所有的User
    getUserList() {
      this.listLoading = true
      // const query={
      //   pageNumber:this.listQuery.page,
      //   pageSize:this.listQuery.limit
      // }
      fetchUserList().then((response) => {
        this.list = response.data.slice((this.listQuery.page - 1) * this.listQuery.limit, this.listQuery.page * this.listQuery.limit)
        this.total = response.data.length
        console.log(this.list)
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },

    // 根据roleid拿到所有的User，如果roleid为空，则默认拿到所有的User
    getUserListPaged() {
      this.listLoading = true
      const query = {
        pageNumber: this.listQuery.page,
        pageSize: this.listQuery.limit
      }
      fetchUserListPaged(query).then((response) => {
        this.list = response.data
        // this.total = response.data.length;
        console.log(this.list)
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },

    getUserListByRoleId() {
      this.listLoading = true
      fetchUserListByRoleId(this.listQuery.roleId).then((response) => {
        this.list = response.data
        this.total = response.data.length

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },

    handleFilter() {
      this.listQuery.page = 1
      // this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined, // 编号
        name: '', // 登录名
        nickName: '', // 昵称
        address: '', // 地址
        roleId: '', // 角色id
        roleName: '', // 角色名称
        sex: '', // 性别
        titlePic: '', // 头像
        password: ''
      }
    },

    handleCreate() {
      // 加载roles
      this.getRolesExceptAdmin()
      // console.log(this.roles);

      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      // 在创建的时候因为前台只提供了username和password，为通过验证，要将rule要求的其他内容补齐
      this.temp.sex = '男'
      // console.log(this.temp);
      // console.log(this.roles);
      // 找到pm对象
      var pm = this.roles.filter((r) => r.name === 'Product Manager')[0]
      // console.log(pm);
      // 找到user对象
      var user = this.roles.filter((r) => r.name === 'User')[0]

      var admin = this.roles.filter((r) => r.name === 'Admin')[0]

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024; // mock a id
          // this.temp.author = "vue-element-admin";
          // createArticle(this.temp).then(() => {
          //   this.list.unshift(this.temp);
          //   this.dialogFormVisible = false;
          //   this.$notify({
          //     title: "Success",
          //     message: "Created Successfully",
          //     type: "success",
          //     duration: 2000,
          //   });
          // });
          // console.log(this.temp);
          const postData = {
            UserName: this.temp.name,
            Password: this.temp.password
          }
          // 一堆错误！！！！！！！！！！！！
          // 如果当前角色类型为User
          if (this.temp.roleId === admin.id) {
            createUser(postData).then((res) => {
              const { data } = res
              // console.log(data);
              // 拿到完整的user
              getInfo(data.userId).then((res) => {
                // this.list.unshift(res.data);
                // 重新加载数据
                this.loadData()

                this.dialogFormVisible = false
                this.$notify({
                  title: 'Success',
                  message: 'Created Successfully',
                  type: 'success',
                  duration: 2000
                })
              })
            })
          }
          // 如果当前角色类型为PM
          else if (this.temp.roleId === pm.id) {
            console.log('createPm')
            createPm(postData).then((res) => {
              const { data } = res
              // console.log(data);
              // 拿到完整的user
              getInfo(data.userId).then((res) => {
                // this.list.unshift(res.data);
                // 重新加载数据
                this.loadData()

                this.dialogFormVisible = false
                this.$notify({
                  title: 'Success',
                  message: 'Created Successfully',
                  type: 'success',
                  duration: 2000
                })
              })
            })
          }
        } else {
          this.$message.error('输入不合法，请重新输入')
          this.resetTemp()
        }
      })
    },

    handleUpdate(row) {
      // 加载roles
      this.getRoles()

      // console.log("handleUpdate");
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp);

      // 在创建的时候因为前台只提供了username和password，为通过验证，要将rule要求的其他内容补齐
      this.temp.password = '******'

      // console.log(this.temp);
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          console.log(tempData)
          const putData = {
            Name: tempData.name,
            Sex: tempData.sex,
            NickName: tempData.nickName,
            TitlePic: tempData.titlePic,
            Address: tempData.address
          }
          UpdateInfo(putData).then(() => {
            const index = this.list.findIndex((v) => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    // `````````````````AscensionAppUser Start```````````````````````
    handleAscensionAppUser(row) {
      // 加入弹窗
      this.$confirm('确认升级此用户等级吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 用户点击确定
          // AscensionAppUser(row);
          const putData = {
            Name: row.name,
            RoleName: row.roleName
          }
          AscensionAppUser(putData).then((res) => {
            const index = this.list.findIndex((v) => v.id === row.id)
            // 拿到更新后的row
            this.list.splice(index, 1, res.data)
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
          // this.$message({
          //   type: 'success',
          //   message: '操作成功!'
          // });
        })
        .catch(() => {
          this.$message({
            // 用户点击取消
            type: 'info',
            message: '用户已取消'
          })
        })
    },
    // `````````````````AscensionAppUser End`````````````````````````

    // `````````````````ReduceAppUser Start```````````````````````
    handleReduceAppUser(row) {
      // 加入弹窗
      this.$confirm('确认降低此用户等级吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 用户点击确定
          // AscensionAppUser(row);
          const putData = {
            Name: row.name,
            RoleName: row.roleName
          }
          ReduceAppUser(putData).then((res) => {
            const index = this.list.findIndex((v) => v.id === row.id)
            // 拿到更新后的row
            this.list.splice(index, 1, res.data)
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
          // this.$message({
          //   type: 'success',
          //   message: '操作成功!'
          // });
        })
        .catch(() => {
          this.$message({
            // 用户点击取消
            type: 'info',
            message: '用户已取消'
          })
        })
    },
    // `````````````````ReduceAppUser End`````````````````````````

    // `````````````````handleChangePassword Start`````````````````
    handleChangePassword(row) {
      this.resetchangePasswordTemp()
      this.dialogStatus = 'changePassword'
      this.changePassworddialogFormVisible = true
      // 更新changePasswordTemp数据
      // this.changePasswordTemp = Object.assign({}, row); // copy obj
      this.changePasswordTemp.id = row.id
      this.changePasswordTemp.name = row.name

      console.log(this.changePasswordTemp)
      this.$nextTick(() => {
        this.$refs['changePasswordDataForm'].clearValidate()
      })
    },
    resetchangePasswordTemp() {
      this.changePasswordTemp.password = '' // 密码
      this.changePasswordTemp.newPassword = ''
      this.changePasswordTemp.confirmNewPassword = ''
    },
    changePassword() {
      this.$refs['changePasswordDataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.changePasswordTemp)
          // tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          const putData = {
            OldPassword: tempData.password,
            NewPassword: tempData.newPassword,
            UserName: tempData.name
          }
          ChangePassword(putData)
            .then(() => {
              // const index = this.list.findIndex((v) => v.id === this.temp.id);
              // this.list.splice(index, 1, this.temp);
              this.changePassworddialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
            })
            .catch(() => {
              this.changePassworddialogFormVisible = false
              this.resetchangePasswordTemp()
            })
        } else {
          // this.resetchangePasswordTemp();
          // this.$refs["changePasswordDataForm"].clearValidate();
        }
      })
    },
    // `````````````````handleChangePassword End`````````````````

    handleDelete(row, index) {
      // 加入弹窗
      this.$confirm('确认删除此用户吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 用户点击确定
          DeleteAppUserInfo(row.id).then((res) => {
            // const index = this.list.findIndex((v) => v.id === row.id);
            // 拿到更新后的row
            // this.list.splice(index, 1, res.data);
            this.$notify({
              title: 'Success',
              message: 'Delete Successfully',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
          // this.$message({
          //   type: 'success',
          //   message: '操作成功!'
          // });
        })
        .catch(() => {
          this.$message({
            // 用户点击取消
            type: 'info',
            message: '用户已取消'
          })
        })
    },

    // handleFetchPv(pv) {
    //   fetchPv(pv).then((response) => {
    //     this.pvData = response.data.pvData
    //     this.dialogPvVisible = true
    //   })
    // },

    // 导出为Excel文件
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = [
          'ID',
          '登录名',
          '昵称',
          '性别',
          '角色类别',
          '头像',
          '地址'
        ]
        const filterVal = [
          'id',
          'name',
          'nickName',
          'sex',
          'roleName',
          'titlePic',
          'address'
        ]
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: new Date() + '用户列表'
        })
        this.downloadLoading = false
      })
    },

    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
